package com.mzj.saas.mservice.sys.service;

import com.mzj.saas.commons.ApiData;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.util.StringUtils;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.sys.entity.WithdrawUser;
import com.mzj.saas.mservice.sys.repository.WithdrawUserRepository;
import com.mzj.saas.mservice.sys.vo.WithdrawUserVO;
import com.mzj.saas.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class WithdrawUserService {
    private Logger LOG = LoggerFactory.getLogger(WithdrawUserService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private WithdrawUserRepository withdrawUserRepository;

    /*
     *新增提现人
     */
    public ResultBean<Object> peopleSet(String accessToken, String userId) {
        LOG.info("---WithdrawUserService peopleSet accessToken={},userId={}", accessToken, userId);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (StringUtils.isBlank(userId)) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            WithdrawUserVO withdrawUserVO = new WithdrawUserVO();
            withdrawUserVO.setUserId(userId);
            withdrawUserVO.setStatus(1);
            withdrawUserVO.setCreateTime(new Date());
            withdrawUserVO.setLastUpdateTime(new Date());
            withdrawUserVO.setOrgId(tokenRedisVo.getEnterpriseId());
            withdrawUserVO.setOperationId(tokenRedisVo.getId());
            WithdrawUser existWithdrawUser = withdrawUserRepository.findByOrgIdAndUserId(tokenRedisVo.getEnterpriseId(), withdrawUserVO.getUserId());
            if (existWithdrawUser != null && existWithdrawUser.getStatus() == 1) {
                return ResultBean.failedResultWithMsg("该提现人已被添加");
            } else if (existWithdrawUser != null && existWithdrawUser.getStatus() == 2) {
                withdrawUserVO.setId(existWithdrawUser.getId());
                withdrawUserVO.setCreateTime(existWithdrawUser.getCreateTime());
            }
            WithdrawUser withdrawUser = new WithdrawUser();
            BeanUtils.copyProperties(withdrawUserVO, withdrawUser);
            withdrawUserRepository.save(withdrawUser);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     *删除提现人
     */
    public ResultBean<Object> peopleDelete(String accessToken, String userId) {
        LOG.info("---WithdrawUserService peopleDelete accessToken={},userId={}", accessToken, userId);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (StringUtils.isBlank(userId)) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            WithdrawUser existWithdrawUser = withdrawUserRepository.findByOrgIdAndUserId(tokenRedisVo.getEnterpriseId(), userId);
            if (existWithdrawUser != null) {
                existWithdrawUser.setStatus(2);
                existWithdrawUser.setOperationId(tokenRedisVo.getId());
                existWithdrawUser.setLastUpdateTime(new Date());
                withdrawUserRepository.save(existWithdrawUser);
            } else {
                return ResultBean.failedResultWithMsg("提现人信息不存在或是已删除");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     *提现人列表显示
     */
    public ResultBean<Object> peopleList(String accessToken, Integer pageNumber, Integer pageSize) {
        LOG.info("---WithdrawUserService peopleList accessToken={}", accessToken);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        ApiData<Map<String, Object>> apiData = new ApiData<>();
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            String sql = "SELECT w.`id`,`org_id` AS orgId,w.user_id AS userId,`name`  FROM `saas_withdraw_user` w INNER JOIN `saas_user` u ON w.user_id=u.id  WHERE w.`org_id`=? AND w.`status`=1   \n";
            String offsets = "  LIMIT ? OFFSET ? ";
            String count = "SELECT COUNT(0) FROM (" + sql + ") c";
            List<Object> args = new ArrayList<>();
            args.add(tokenRedisVo.getEnterpriseId());
            // 查询总记录数
            Long total = jdbcTemplate.queryForObject(count, args.toArray(), Long.class);
            if (total == 0) {
                result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
                result.setResultData(null);
                return result;
            }
            // 查询分页数据
            sql += offsets;
            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<Map<String, Object>> peopleList = jdbcTemplate.queryForList(sql, args.toArray());
            apiData.setData(peopleList);
            apiData.setTotal(total);
            result.setResultData(apiData);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }
}
